package com.itheima.security;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Martin MYZ
 * @create 2019-07-19-8:46
 */

public class SpringSecurityUserService implements UserDetailsService {

    /**
     * 注入密码加密对象,对密码进行加密
     */
    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名,查询数据库,获得User
        User user = findUserByName(username);
        //判断是否为null
        if(user == null){
            return null;
        }
        //把用户名,数据库的密码,以及查询出来的权限访问,创建UserDetails对象并返回
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("add"));
        list.add(new SimpleGrantedAuthority("delete"));
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        org.springframework.security.core.userdetails.User userDetails
                = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);

        return userDetails;
    }

    //模拟从数据库查询
    private User findUserByName(String username) {
        if("admin".equals(username)){
            User user = new User();
            user.setUsername(username);
            user.setPassword(encoder.encode("123456"));
            return user;
        }
        return  null;
    }
}
